from project.courses_system.algorithm.course_system import CourseManagementSystem
import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).parent.parent.parent))
from project.courses_system.algorithm.course_system import CourseManagementSystem
from project.courses_system.data import load_data
def get_user_input_with_suggestions(prompt, system, search_type=None):
    while True:
        user_input = input(prompt).strip()
        if not user_input:
            print("Please enter at least one character")
            continue
        
        if search_type:
            suggestions = system.search_suggestions(search_type, user_input)
            if suggestions:
                print("\nDid you mean these?")
                for i, sug in enumerate(suggestions, 1):
                    print(f"{i}. {sug['display']}")
                print(f"{len(suggestions)+1}. None of these")
                while True:
                    choice = input("Select number or press Enter to continue: ").strip()
                    if choice.isdigit() and 0 < int(choice) <= len(suggestions):
                        return suggestions[int(choice)-1]['id']
                    elif choice == str(len(suggestions)+1):
                        print(f"⚠️ No matching {search_type} found for '{user_input}'.No such student.")
                        break
                    else:
                        print("enter a valid choice!")
                        continue
        return user_input

def main():
    students = load_data(Path(__file__).parent.parent.parent / 'ressources' / 'students.json')
    classes = load_data(Path(__file__).parent.parent.parent / 'ressources' / 'classes.json')
    courses = load_data(Path(__file__).parent.parent.parent / 'ressources' / 'courses.json')
    grades = load_data(Path(__file__).parent.parent.parent / 'ressources' / 'grades.json')
    
    system = CourseManagementSystem(students, classes, courses, grades)
    def ask_continue(prompt):
        while True:
            choice = input(f"{prompt} (y/n): ").lower()
            if choice in ['y', 'yes']:
                return True
            elif choice in ['n', 'no']:
                return False
            print("Please enter 'y' or 'n'")
    print(f"Welcome to this app!")
    print("===================")
    while True:
        print(f"Choose one function:\n0.Help\n1.search for all students/courses\n2.get information about studnets or courses\n3.search for a student grade\n4.Student roster of a course\n5.check a student's schedule\n6.sort students\n7.add course\n8.Exit")
        user_input1 = input("Which feature do you want to explore? ")
        user_input1 = user_input1.upper()
        if not user_input1:
            print("please enter a section!")
        if user_input1 == '0':
            while True:
                print("---------Help---------\n1.This app is mainly used for course management\n2.if you don't know students and courses,you can open file1 and have a look\n3.You can just type a letter and press enter to get a hint\n----------------------")
                input2 = input("Exit the help menu and return to the table of contents?(enter 'y') ")
                if input2 == 'y':
                    break
                
        if user_input1 == '1':
            while True:
                user_input2 = input("Do you want to get to know the students or the curriculum?(enter 'std' or 'course'/enter 'back' to exit) ")
                if user_input2 == 'back':
                    break
                elif user_input2 == 'std':
                    print(system.display_all_students())
                elif user_input2 == 'course':
                    print(system.display_all_courses())
                else:
                    raise ValueError('enter valid choice ')
                if not ask_continue('Do you want to take another look? '):
                    break
        if user_input1 == '2':
            
            while True:
                user_input2 = get_user_input_with_suggestions(
                "May we know which area do you want to know? (enter 'course' or 'std'/enter 'back' to exit): ",
                system, None
            ).lower()
                if user_input2 == 'back':
                    break

                elif user_input2 == 'course':
                    while True:  
                        course_input = get_user_input_with_suggestions(
                            "Please enter the course name (start typing for suggestions, or 'back' to return): ",
                            system, 'course'
                        )

                        if course_input.lower() == 'back':
                            break

                        course_message = system.display_course_information(course_input)
                        if course_message:
                            print(course_message)
                        else:
                            print("Course not found")

                        if not ask_continue("Would you like to search for another course? "):
                            break
                        
                elif user_input2 == 'std':
                    while True:  
                        student_input = get_user_input_with_suggestions(
                            "Please enter the student name (start typing for suggestions, or 'back' to return): ",
                            system, 'student'
                        )

                        if student_input.lower() == 'back':
                            break

                        student_message = system.display_student_information(student_input)
                        if student_message:
                            print(student_message)
                        else:
                            print("Student not found")

                        if not ask_continue("Would you like to search for another student? "):
                            break

        elif user_input1 == '3':
            while True:
                user_input2 = get_user_input_with_suggestions(
                    "May we know which student's grade do you want to know? (enter student name/enter 'back' to exit): ",
                    system, 'student'
                ).lower()
                if user_input2.lower() == 'back':
                    break
                
                grade_message = system.display_student_grades(user_input2)
                if grade_message:
                    print(grade_message)
                else:
                    print('No grade record for this student')

                if not ask_continue("Search for another student grade? "):
                    break

        elif user_input1 == '4':
                
            while True:
                user_input2 = get_user_input_with_suggestions(
                    "Enter course ID to view roster (or 'back' to return): ",
                    system, 'course'
                )

                if user_input2.lower() == 'back':
                    break
                
                roster = system.display_course_students(user_input2)

                if roster is None:  
                    print(f"❌ Error: Course {user_input2} does not exist")
                elif not roster:    
                    print(f"ℹ️ No students enrolled in {user_input2}")
                else:
                    print(f"✅ Students enrolled in {user_input2}:")
                    for i, student in enumerate(roster, 1):
                        print(f"  {i}. {student}")

                if not ask_continue("View another course's roster? "):
                    break

        elif user_input1 == '5':
            while True:
                user_input2 = get_user_input_with_suggestions(
                    "May we know You want to know which student's course schedule?(enter student name/enter 'back' to exit): ",
                    system, 'student'
                ).lower()
                if user_input2 == 'back':
                    break
                check_schedule = system.check_schedule_conflicts(user_input2)
                if check_schedule:
                    print(f"{check_schedule}\n")
                elif not check_schedule:
                    print("the student has no class confliction")
                elif check_schedule is None:
                    print("No such student")
                if not ask_continue("Check more students' schedule? "):
                    break
                

        elif user_input1 == '6':
            while True:
                user_input2 = get_user_input_with_suggestions(
                    "May we know the way you want to sort students?(enter 'name','username','grade'/enter 'back' to exit): ",
                    system, None
                ).lower()
                if user_input2 == 'back':
                    break
            
                if user_input2 == 'name':
                    print("\nA list of students sorted by name: ")
                    name_sorted = system.display_name_sorted('name')
                    for student in name_sorted:
                        print(f"{student['index']:>4}\tname:{student['full name']:<16}\tusername:{student['username']:<20}\tage:{student['age']}")
                elif user_input2 == 'username':
                    print("\nA list of students sorted by username: ")
                    user_sorted = system.display_name_sorted('username')
                    for student in user_sorted:
                        print(f"{student['index']:>4}\tusername:{student['username']:<16}\tname:{student['full name']:<20}\tintersts:{student['interests']}")
                elif user_input2 == 'grade':
                    while True:
                        user_input3 = get_user_input_with_suggestions(
                        "May we know the course ID you want to use?(enter course ID/enter 'back' to exit): ",
                        system,'course'
                        ).upper()
                        if user_input3:
                            print("\nCourse Grade Rankings: ")
                            ranking = system.display_course_ranking(user_input3)
                            if ranking:
                                print(f"=== {user_input3} Course Grade Rankings ===")
                                print(f"{'ranking':<14} {'username':<20} {'average score':<15}   {'all time scores':<25}")
                                for rank, username, avg, scores in ranking:
                                    print(f"{rank:<8}\t{username:<20}\t{avg:<10.2f}\t{scores}")
                            elif ranking is None:
                                print(f"❌ Error: Course {user_input3} ranking does not exist") 
                                if not ask_continue("Try another class? "):
                                    break
                                continue
                        elif not user_input3:
                                print("please enter valid class ID")
                        elif user_input3 == 'back':
                            break
                        if not ask_continue("See more course rankings? "):
                            break
                            
                if not ask_continue('See results sorted in more ways? '):
                    break

        elif user_input1 == '7':
            while True:
                student = get_user_input_with_suggestions(
                    "Enter student username:(/or enter 'back' to exit) ",
                    system, 'student')
                course = get_user_input_with_suggestions(
                    "Enter course ID to enroll:(/or enter 'back' to exit) ",
                    system, 'course')
                if student == 'back' or course == 'back':
                    break
                result = system.enroll_student(student, course)
                print(result)
                if not ask_continue('Add more new course? '):
                    break

        elif user_input1 == '8':
            input2 = input("Are you sure you want to quit?(y/n) ")
            input2 =input2.upper()
            if input2 == 'Y':
                print("Thank you for using")
                break

if __name__ == "__main__":
    main()